package com.hfzy.ihk.common.web.converter.customEnum;

import com.hfzy.ihk.common.facade.CustomEnumType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Created by Administrator on 2018/1/22.
 *
 * 接收页面的
 * @author wws
 */
public class StringToCustomEnumTypeConverterFactory implements ConverterFactory<String, CustomEnumType> {

    private static Logger logger = LoggerFactory.getLogger(StringToCustomEnumTypeConverterFactory.class);
    private static final Map<Class, Converter> converterMap = new WeakHashMap<>();

    @Override
    public <T extends CustomEnumType> Converter<String, T> getConverter(Class<T> targetType) {
        logger.info("StringToCustomEnumType转换到:"+targetType.getName());
        Converter result = converterMap.get(targetType);
        if(result == null) {
            result = new StringToEnum<T>(targetType);
            converterMap.put(targetType, result);
        }
        return result;
    }

    /**
     *
     * */
    class StringToEnum<T extends CustomEnumType> implements Converter<String, T> {

        private final Class<T> enumType;

        private Map<String, T> enumMap = new HashMap<>();

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
            T[] enums = enumType.getEnumConstants();
            for(T e : enums) {
                enumMap.put(e.getValue(), e);
            }
        }


        @Override
        public T convert(String source) {

            T result = enumMap.get(source);
            if(result == null) {
                throw new IllegalArgumentException("CustomEnumType field转换失败,类型:"+enumType.getName()+"不存在枚举值：" + source);
            }
            return result;
        }
    }

}
